package com.wonder.framework.authorization;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wonder.common.constants.Constants;
import com.wonder.common.exception.XhadminException;
import com.wonder.framework.authorization.TokenAdminManager;
import com.wonder.framework.redis.RedisCache;
import com.wonder.common.utils.ThreadLocalUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class CheckAdminToken {


    @Autowired
    protected RedisCache redisCache;
    
    @Autowired
    protected TokenAdminManager tokenManager;

    public Boolean check(String token){

        try {
            boolean exists = redisCache.exists(Constants.ADMIN_TOKEN_KEY + token);
            if(exists){
                Object value = redisCache.get(Constants.ADMIN_TOKEN_KEY + token);

                Map<String, Object> hashedMap = new HashMap<>();
                hashedMap.put("id", value);
                ThreadLocalUtil.set(hashedMap);

                redisCache.set(Constants.ADMIN_TOKEN_KEY +token, value, Constants.TOKEN_EXPRESS_MINUTES, TimeUnit.MINUTES);
            }
            return exists;
        }catch (Exception e){
            return false;
        }
    }

    public String getTokenFormRequest(HttpServletRequest request){
        String pathToken =request.getParameter(Constants.HEADER_AUTHORIZATION_KEY);
        if(null != pathToken){
            return pathToken;
        }
        return request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);
    }
    
    public Long getUserIdByToken(HttpServletRequest request) {
    	
		String token=getTokenFormRequest(request);
		Boolean tokenExsit = tokenManager.checkToken(token, Constants.ADMIN_TOKEN_KEY);
        if(!tokenExsit){
            throw new XhadminException("user.token.not.effect");
        }
        return tokenManager.getToken(token, Constants.ADMIN_TOKEN_KEY);
	}

}
